package servlets;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * DownloadServlet implementation class ServerServlet - for download a file
 * answer urls: .../DownloadServlet + .../DownloadServlet/*
 */
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * url: ....../checksum/fileName
	 * download a file
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		//get the fileName and it's checksum
		String fileName = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/")+1);
		String withoutFileName = request.getRequestURI().substring(0,request.getRequestURI().lastIndexOf("/"));
		String checksum = withoutFileName.substring(withoutFileName.lastIndexOf("/")+1);
		
		BufferedInputStream buf=null;
		ServletOutputStream myOut=null;

		try{

			 myOut = response.getOutputStream( );
		
			 //find the file we want to send to the client
		     File myfile = new File(".\\files\\"+checksum+fileName.substring(fileName.lastIndexOf(".")));
		     
		     //set response headers
		     response.setContentType("text/plain");
		     
		     response.addHeader(
		        "Content-Disposition","attachment; filename="+fileName );

		     response.setContentLength( (int) myfile.length( ) );
		     
		     FileInputStream input = new FileInputStream(myfile);
		     buf = new BufferedInputStream(input);
		     int readBytes = 0;

		     //read from the file; write to the ServletOutputStream
		     while((readBytes = buf.read( )) != -1)
		       myOut.write(readBytes);

		 } catch (IOException ioe){
		     
		        throw new ServletException(ioe.getMessage( ));
		         
	     } finally {
	         
	     //close the input/output streams
	         if (myOut != null)
	             myOut.close( );
	          if (buf != null)
	          buf.close( );
	         
	     }         
        
	}

	/**
	 * do nothing
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
 
	}
	
	


	
	
}
